package com.manage.web.controller;

import com.manage.dao.IClazzDao;
import com.manage.domain.Student;
import com.manage.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;
    @Autowired
    private IClazzDao clazzDao;

    @RequestMapping("/list.do")
    public String list(Model model) {
        List<Student> list = studentService.list();
        model.addAttribute("list", list);
        model.addAttribute("clazzList", clazzDao.list());
        return "student-list";
    }

    @RequestMapping(value = "/add.do", method = RequestMethod.POST)
    public String add(Student s, 
                     @RequestParam(required = false, name = "graduationDateStr") String graduationDate,
                     Model model) {
        try {
            System.out.println("接收到的学员数据: " + s.getName() + ", " + s.getGender() + ", " + s.getPhone() + ", " + s.getClazzId());
            // 手动处理日期转换
            if (graduationDate != null && !graduationDate.trim().isEmpty()) {
                s.setGraduationDate(LocalDate.parse(graduationDate));
            }
            studentService.add(s);
            return "redirect:/student/list.do";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "新增学员失败: " + e.getMessage());
            return list(model);
        }
    }

    @RequestMapping("/update.do")
    public String update(Student s, 
                        @RequestParam(required = false, name = "graduationDateStr") String graduationDate,
                        Model model) {
        try {
            // 手动处理日期转换
            if (graduationDate != null && !graduationDate.trim().isEmpty()) {
                s.setGraduationDate(LocalDate.parse(graduationDate));
            }
            studentService.update(s);
            return "redirect:/student/list.do";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "修改学员失败: " + e.getMessage());
            return list(model);
        }
    }

    @RequestMapping("/delete.do")
    public String delete(@RequestParam Integer id) {
        studentService.delete(id);
        return "redirect:/student/list.do";
    }
}


